package br.com.salaodebeleza.ws;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class ClienteWS {

	static final String CHAMADA = "" +
			"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">" +
			" <soapenv:Header/> " +
			" <soapenv:Body> " +
			"  <tem:dsAutenticarUsuario> " +
			"    <!--Optional:--> " +
			"    <tem:strIdUsuario>##id##</tem:strIdUsuario> " +
			"    <!--Optional:--> " +
			"    <tem:strSenhaUsuario>##pass##</tem:strSenhaUsuario> " +
			"    <!--Optional:--> " +
			"    <tem:strtCodigoSite>##site##</tem:strtCodigoSite> " +
			"  </tem:dsAutenticarUsuario> " +
			" </soapenv:Body> " +
			" </soapenv:Envelope> ";

	public UserLogin loginWS(String id, String pass, String site) {

		String chamadaWS = CHAMADA;
		chamadaWS = chamadaWS.replace("##id##", id);
		chamadaWS = chamadaWS.replace("##pass##", pass);
		chamadaWS = chamadaWS.replace("##site##", site);

		UserLogin retorno = new UserLogin();

		try {
			// Create the connection
			SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
			SOAPConnection conn = scf.createConnection();

			// Create message
			MessageFactory mf = MessageFactory.newInstance();
			SOAPMessage msg = mf.createMessage();

			MimeHeaders mimeHeader = msg.getMimeHeaders();
			//change header's attribute  
			mimeHeader.setHeader("SOAPAction", "http://tempuri.org/dsAutenticarUsuario");

			// Object for message parts
			SOAPPart sp = msg.getSOAPPart();
			StreamSource prepMsg = new StreamSource(new ByteArrayInputStream(chamadaWS.getBytes()));
			sp.setContent(prepMsg);

			// Save message
			msg.saveChanges();

			// View input 
			System.out.println("\n Soap request:\n");
			msg.writeTo(System.out);
			System.out.println();

			// Send
			String urlval = "http://www.soa.intranet/project_soa_autenticacao/ws_soa_autenticacao.asmx";
			SOAPMessage rp = conn.call(msg, urlval);

			Document doc = ClienteWS.messageToDocument(rp);
			String id_user = doc.getElementsByTagName("ID_USER").item(0).getTextContent();
			String nome = doc.getElementsByTagName("NOME").item(0).getTextContent();
			String cdi = doc.getElementsByTagName("CDICONTRATADO").item(0).getTextContent();
			String grupo = doc.getElementsByTagName("DESC_GRUPO").item(0).getTextContent();
			String filial = doc.getElementsByTagName("FILIAL_ATU").item(0).getTextContent();
			
			String cargo = doc.getElementsByTagName("CARGO").item(0).getTextContent();
			String chapa = doc.getElementsByTagName("CHAPA").item(0).getTextContent();
			String cpf = doc.getElementsByTagName("CPF").item(0).getTextContent();
			String email = doc.getElementsByTagName("EMAIL").item(0).getTextContent();

			retorno.setId(id_user);
			retorno.setNome(nome);
			retorno.setCdi(cdi);
			retorno.setGrupo(grupo);
			retorno.setFilial(filial);
			
			retorno.setCargo(cargo);
			retorno.setChapa(chapa);
			retorno.setCpf(cpf);
			retorno.setEmail(email);

			// Close connection
			conn.close();

		}
		catch (Exception e) {
			System.out.println(e.getMessage());
			retorno = null;
		}finally{
			
		}
		return retorno;
	}
	public static Document messageToDocument(SOAPMessage message) throws Exception {  
		try {  
			Source content = message.getSOAPPart().getContent();  
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
			dbf.setNamespaceAware(true);  
			DocumentBuilder builder = dbf.newDocumentBuilder();  
			return builder.parse(sourceToInputSource(content));  
		} catch (Exception ex) {  
			throw ex;  
		}  
	}

	public static InputSource sourceToInputSource(Source source) {
		if (source instanceof SAXSource) {
			return ((SAXSource) source).getInputSource();
		} else if (source instanceof DOMSource) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			Node node = ((DOMSource) source).getNode();
			if (node instanceof Document) {
				node = ((Document) node).getDocumentElement();
			}
			Element domElement = (Element) node;
			ElementToStream(domElement, baos);
			InputSource isource = new InputSource(source.getSystemId());
			isource.setByteStream(new ByteArrayInputStream(baos.toByteArray()));
			return isource;
		} else if (source instanceof StreamSource) {
			StreamSource ss = (StreamSource) source;
			InputSource isource = new InputSource(ss.getSystemId());
			isource.setByteStream(ss.getInputStream());
			isource.setCharacterStream(ss.getReader());
			isource.setPublicId(ss.getPublicId());
			return isource;
		} else {
			return getInputSourceFromURI(source.getSystemId());
		}
	}

	/**
	 * Utility to get the bytes uri.
	 * Does NOT handle authenticated URLs,
	 * use getInputSourceFromURI(uri, username, password)
	 *
	 * @param uri the resource to get
	 */
	public static InputSource getInputSourceFromURI(String uri) {
		return new InputSource(uri);
	}

	public static void ElementToStream(Element element, OutputStream out) {
		try {
			DOMSource source = new DOMSource(element);
			StreamResult result = new StreamResult(out);
			TransformerFactory transFactory = TransformerFactory.newInstance();
			Transformer transformer = transFactory.newTransformer();
			transformer.transform(source, result);
		} catch (Exception ex) {
		}
	}

}
